// 引入数据模型
const { Item, User, Comment } = require("../model/index")
const { getItemAllComments } = require('./comment')

/**
 * 获取全部商品
 * @param {number} categoryId 商品类别id
 * @returns 
 */
// exports.getAllItems = async function (categoryId) {
//   //查询
//   const result = await Item.findAll({
//     where: {}
//   })

//   return result
// }

/**
 * 获取全部商品并分页
 * @param {number} categoryId 商品类别id
 * @returns 
 */
exports.getAllAndCountItems = async function ({ categoryId, pageNum = 1, pageSize = 4 }) {
  if (!categoryId) {
    return null
  }
  const whereOpt = { categoryId }
  //查询
  const { count, rows: items } = await Item.findAndCountAll({
    where: whereOpt,
    limit: pageSize,
    offset: (pageNum - 1) * pageSize,
    order: [
      ['id', 'desc']
    ]
  })

  return {
    count,
    items: items,
    pageNum,
    pageSize
  }
}

/**
 * 获取单个商品
 * @param {number} id 商品id
 * @returns Object
 */
exports.getItem = async function (id) {
  const whereOpt = {}
  if (id) {
    whereOpt.id = id
  }
  //查询商品详细信息
  const result = await Item.findOne({
    where: whereOpt
  })
  // 查询商品所有评论并分页
  const { count, comments, pageNum, pageSize } = await getItemAllComments({ itemId: id })
  return {
    item: result,
    count,
    comments,
    pageNum,
    pageSize
  }
}
